//
//  TTShopCartViewController.m
//  TaoTuo
//
//  Created by admin on 2019/8/15.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTShopCartViewController.h"
#import "TTUserModel.h"
#import "TTShopCartModel.h"
#import "TTShopCartDiamondViewCell.h"
#import "TTShopCartCommodityViewCell.h"
#import "TTShopCartMultyViewCell.h"
#import "TTShopCartMultyModel.h"
#import "TTGoodsDetailViewController.h"
#import "YBImageBrowser.h"
#import "TTDiamondDetailViewController.h"
#import "TTCommitOrderViewController.h"
#import "TTDiamondsRecommendModel.h"
#import "LLListView.h"
#import <UIView+TYAlertView.h>

#define bottomViewH 50 * kScale

static NSString *luoshiCellID = @"shop_cart_luoshi_cell_id";        // 裸石
static NSString *commodityCellID = @"shop_cart_commodity_cell_id";  // 商品
static NSString *multyCellID = @"shop_cart_multy_cell_id";      // 一个cell里面有多个商品的

@interface TTShopCartViewController ()<UITableViewDelegate, UITableViewDataSource, TTShopCartDiamondViewCellDelegate, TTShopCartCommodityViewCellDelegate, TTShopCartMultyViewCellDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UIButton *deleteBtn;

@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UILabel *topLabel;

@property (nonatomic, strong) UIView *redView; // 红色置顶view

@property (nonatomic, strong) NSMutableArray *allSubDetailModelsArray;  // 所有的展示出来的数据model
@property (nonatomic, strong) NSMutableArray<NSString *> *deleteIDArray;  // 选中的要删除的数组
@property (nonatomic, strong) NSMutableArray<TTShopCartSubDetailModel *> *deleteArray;  // 要删除的model
@property (nonatomic, strong) NSMutableArray<TTShopCartSubDetailModel *> *selectedArray;    // 选中的商品
@property (nonatomic, strong) TTDiamondsRecommendModel *diamondModel;

@property (nonatomic, strong) UIView *bottomView;  // 底部
@property (nonatomic, strong) UIButton *allSelectBtn;   // 全选
@property (nonatomic, strong) UILabel *totalLabel;  // 合计
@property (nonatomic, strong) UIButton *calculateBtn;   // 结算

@property (nonatomic, assign) CGFloat totalPrice;   // 总价

@property (nonatomic, strong) UIView *emptyView;    // 无数据展示
///提示删除或加入收藏夹
@property (nonatomic, strong) UIView *hintView;
@property (nonatomic, strong) UIButton *longPressDeleteBtn;  //裸石长按删除
///长按弹出的alertView
@property (nonatomic, strong) UIView *longPressAlertView;
///需要通知详情刷新数据
@property (nonatomic, assign) BOOL needNotifyDetailReloadData;

///要删除的商品
@property (nonatomic, strong) TTShopCartSubDetailModel *deleteModel;

@end

@implementation TTShopCartViewController

- (UIView *)listView
{
    return self.view;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//    if (![TTLoginSingle sharedSingle].isLogin) {
//        [self presentLoginViewControllerWithCloseBlock:^{
//            UITabBarController *rootVC = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
//            [rootVC setSelectedIndex:0];
//        }];
//    }
    [[TTLoginSingle sharedSingle].shopCartSelectBtnSubject sendNext:@(1)];
    self.navigationController.navigationBar.alpha = 1;

    if (self.navigationController.viewControllers.count > 1) {
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"nav_back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(backAction)];
    }

}


//- (void)listDidDisappear
//{
//    BOOL need = NO;
//    for (UIViewController *vc in self.navigationController.viewControllers) {
//        if ([vc isKindOfClass:[TTGoodsDetailViewController class]]) {
//            need = YES;
//            break;
//        }
//    }
//    if (self.needNotifyDetailReloadData && need) {
//        // 通知详情页面刷新数据
//        self.needNotifyDetailReloadData = NO;
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"shopcartdeletedata" object:nil];
//    }
//}

- (void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"购物车";
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [deleteBtn setTitle:@"删除" forState:UIControlStateNormal];
    [deleteBtn setTitleColor:[UIColor grayColor] forState:UIControlStateDisabled];
    [deleteBtn setTitleColor:kMainColor forState:UIControlStateNormal];
    deleteBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    deleteBtn.frame = CGRectMake(0, 0, 44, 44);
    [deleteBtn addTarget:self action:@selector(deleteButtonClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *deleteItem = [[UIBarButtonItem alloc] initWithCustomView:deleteBtn];
    
    UIBarButtonItem *dotItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"threedot"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(removeSelloutShop)];    // 清空已售的产品
    self.navigationItem.rightBarButtonItems = @[dotItem, deleteItem];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteButtonClick) name:@"shopCart_delete_notify_key" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleDeleteDatas) name:@"shopCart_removeSellout_notify_key" object:nil];
    
    self.deleteBtn = deleteBtn;
    self.deleteBtn.enabled = NO;
    
    
    [self getShopCartData];
    @weakify(self)
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        @strongify(self)
        [self getShopCartData];
        [TTCommonNetData getShopCartCodeInfoSuccess:^(NSArray * _Nonnull cartCodeArray, int shopCount) {} failure:^{}];
        self.calculateBtn.enabled = NO;
        self.calculateBtn.backgroundColor = [UIColor grayColor];
        self.deleteBtn.enabled = NO;
    }];
    
    [[TTLoginSingle sharedSingle].shopCartSubject subscribeNext:^(id  _Nullable x) {
        @strongify(self)
        [self getShopCartData];
    }];
    
    [[TTLoginSingle sharedSingle].shopCartSelectBtnSubject subscribeNext:^(id  _Nullable x) {
        @strongify(self)
        // 1.设置删除按钮
        BOOL has = NO;
        for (TTShopCartSubDetailModel *model in self.allSubDetailModelsArray) {
            if (model.isSelect) {
                has = YES;
                break;
            }
        }
        deleteBtn.enabled = has;
        self.calculateBtn.enabled = has;
        UIColor *color = has ? UIColorHex(6928BA) : [UIColor grayColor];
        self.calculateBtn.backgroundColor = color;
        // 2.设置全选按钮
        BOOL allSel = YES;
        for (TTShopCartSubDetailModel *model in self.allSubDetailModelsArray) {
            if (!model.isSelect && model.Status.intValue == 1) {
                allSel = NO;
                break;
            }
        }
        BOOL allSelectBtnEnabled = NO;
        for (TTShopCartSubDetailModel *model in self.allSubDetailModelsArray) {
            if (model.Status.intValue == 1) {
                allSelectBtnEnabled = YES;
                break;
            }
        }
        if (self.allSubDetailModelsArray.count == 0) {
            allSel = NO;
        }
        if (allSelectBtnEnabled) {
            self.allSelectBtn.selected = allSel;
        }
        // 3. 设置价格总和
        self.totalPrice = 0;
        [self.selectedArray removeAllObjects];
        for (TTShopCartSubDetailModel *model in self.allSubDetailModelsArray) {
            if (model.isSelect) {
                CGFloat price = [model.GoodsPrice floatValue];
                self.totalPrice += price * model.Number;
                [self.selectedArray addObject:model];
            }
        }
        
        self.totalLabel.text = [NSString stringWithFormat:@"合计:￥%.0f", self.totalPrice];
        
    }];
    
    
    [[TTLoginSingle sharedSingle].loginSubject subscribeNext:^(id  _Nullable x) {
        @strongify(self)
        if ([x intValue] == 1) {
            // 登录成功
            [self getShopCartData];
        }
    }];
    
}

// 清空已售的产品
- (void)removeSelloutShop
{
    CGRect rect = CGRectMake(self.view.width - 130, StatusBarAndNavBar_Height, 120, 44);
    @weakify(self)
    [LLListView showWithFrame:rect Images:@[@"lajitong"] Titles:@[@"清空已售"] MenuType:ListViewMenuType_ScaleBasedTopRight ClickItem:^(NSInteger index, NSString *title) {
        @strongify(self)
        [self handleDeleteDatas];
    } triangleViewSpaceRight:40];
    
    
}

- (void)handleDeleteDatas
{
    [self.deleteIDArray removeAllObjects];
    [self.deleteArray removeAllObjects];
    for (TTShopCartSubDetailModel *model in self.allSubDetailModelsArray) {
        if (model.Status.intValue != 1) {
            [self.deleteIDArray addObject:model.Id];
            [self.deleteArray addObject:model];
        }
    }
    
    [self deleteShopCartData];
}

// 删除商品
- (void)deleteButtonClick
{
    LLSystemAlertView *alertView = [LLSystemAlertView alertViewWithTitle:@"提示" message:@"确定要删除该商品吗?" cancelTitle:@"取消" cancelBlock:^{
        
    } confirmTitle:@"确定" confirmBlock:^BOOL{
        
        [self.deleteIDArray removeAllObjects];
        [self.deleteArray removeAllObjects];
        for (TTShopCartSubDetailModel *model in self.allSubDetailModelsArray) {
            if (model.isSelect) {
                [self.deleteIDArray addObject:model.Id];
                [self.deleteArray addObject:model];
            }
        }
        
        [self deleteShopCartData];
        
        return YES;
    }];
    
    [alertView showInWindowWithBackgoundTapDismissEnable:YES];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    TTShopCartModel *model = self.dataArray[section];
    return model.DataList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTShopCartModel *model = self.dataArray[indexPath.section];
    TTShopCartSubModel *subModel = model.DataList[indexPath.row];
    if (subModel.Data.count > 1) {
        // 包含多个
        TTShopCartMultyViewCell *cell = [tableView dequeueReusableCellWithIdentifier:multyCellID];
        [cell setMultyModel:subModel.multyModel canSelect:YES sectionViewCanSelect:YES];
        cell.delegate = self;
        return cell;
    } else {
        // 只有一个元素
        TTShopCartSubDetailModel *detailModel = subModel.Data.firstObject;
        if (detailModel.GoodsType == 1) {
            // 裸石
            TTShopCartDiamondViewCell *cell = [tableView dequeueReusableCellWithIdentifier:luoshiCellID];
            [cell setDetailModel:detailModel hasShadow:YES canSelect:YES];
            cell.delegate = self;
            return cell;
        } else {
            TTShopCartCommodityViewCell *cell = [tableView dequeueReusableCellWithIdentifier:commodityCellID];
            [cell setDetailModel:detailModel hasShadow:YES canSelect:YES];
            cell.delegate = self;
            return cell;
        }
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTShopCartModel *model = self.dataArray[indexPath.section];
    TTShopCartSubModel *subModel = model.DataList[indexPath.row];
    if (subModel.Data.count == 1) {
        TTShopCartSubDetailModel *detailModel = subModel.Data.firstObject;
        if (detailModel.GoodsType == 1) {
            // 可售的裸石才能点进去
            if (detailModel.Status.intValue == 1) {
                @weakify(self)
                TTDiamondDetailViewController *diamondDetailVC = [[TTDiamondDetailViewController alloc] initWithDiamondModel:nil diamondID:detailModel.GoodsBarCode];
                diamondDetailVC.dismissBlock = ^{
                    @strongify(self)
                    [self getShopCartData];
                };
                [[LLRouteTool getCurrentNavigationController] pushViewController:diamondDetailVC animated:YES];
            }
            
        } else {
            TTShopCartSubDetailModel *detailModel = subModel.Data.firstObject;
            TTGoodsDetailViewController *detailVC = [[TTGoodsDetailViewController alloc] initWithStyleLibraryId:detailModel.StyleLibraryId model:nil];
//            detailVC.styleLibraryId = detailModel.StyleLibraryId;
            [[LLRouteTool getCurrentNavigationController] pushViewController:detailVC animated:YES];
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTShopCartModel *model = self.dataArray[indexPath.section];
    TTShopCartSubModel *subModel = model.DataList[indexPath.row];
    if (subModel.Data.count > 1) {
        // 包含多个
        return subModel.multyModel.cellHeight + 40 + 10; // 加上区头高度
    } else {
        // 只有一个元素
        TTShopCartSubDetailModel *detailModel = subModel.Data.firstObject;
        return detailModel.h;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    TTShopCartModel *model = self.dataArray[section];
    NSString *title = [model.CreateTime stringByReplacingOccurrencesOfString:@"/" withString:@"-"];
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 30)];
    view.backgroundColor = [UIColor whiteColor];
    UILabel *label = [UILabel labelWithTitle:title color:UIColorHex(666666) fontSize:12];
    label.frame = CGRectMake(15, 0, view.width - 20, view.height);
    [view addSubview:label];
    return view;
}

- (void)deleteShopCartData
{
    if (self.deleteIDArray.count == 0) {
        return;
    }
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] postJsonWithUrlString:deleteShopcart_api parameters:@{@"ShoppingCartId" : self.deleteIDArray} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        //刷新购物车
        [self getShopCartData];
        
        [self.allSubDetailModelsArray removeObjectsInArray:self.deleteArray];
        [self.deleteIDArray removeAllObjects];
        [self.deleteArray removeAllObjects];
        
        [TTCommonNetData handleShopCartCodeInfoWithArray:responseObject[@"StockBarCodeList"]];
        
        [[TTLoginSingle sharedSingle].shopCartSelectBtnSubject sendNext:@(1)];
        self.needNotifyDetailReloadData = YES;
        // 通知tabbar中的购物车刷新数据
        [[NSNotificationCenter defaultCenter] postNotificationName:@"shopcartdeletedataAndRefreshData" object:nil];
        [LLAnimationAlertView dismissView:self.longPressAlertView];
        NSLog(@"--> 删除成功");
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        NSLog(@"--> 删除失败");
        @strongify(self)
        [LLAnimationAlertView dismissView:self.longPressAlertView];
    } showLoadingInView:self.view];
}

- (void)getShopCartData
{
    if (![TTLoginSingle sharedSingle].isLogin) {
        self.emptyView.hidden = NO;
        return;
    }
    NSString *isOldUser = [TTLoginSingle sharedSingle].userModel.IsOldUser ? @"true" : @"false";
    NSDictionary *dic = @{@"param.isOldUser" : isOldUser};
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:getShopCartList_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        // 1. 头
        [self setupHeaderView];
        NSString *headerString = @"";
        for (NSDictionary *dic in responseObject[@"Statistics"]) {
            NSArray *arr = dic[@"Detail"];
            headerString = [NSString stringWithFormat:@"%@%@%@\n", headerString, dic[@"Name"], [arr componentsJoinedByString:@" "]];
        }
        if (headerString.length > 0) {
            headerString = [headerString substringToIndex:headerString.length - 1];
            CGFloat h = [headerString boundingRectWithSize:CGSizeMake(self.view.width - 20, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : self.topLabel.font} context:nil].size.height;
            self.topLabel.height = h;
            self.headerView.height = self.topLabel.height + 10;
        } else {
            self.topLabel.height = 0;
            self.headerView.height = 0;
        }
        self.topLabel.text = headerString;
        
        
        
        // 1.1 裸石相关
        self.diamondModel = [TTDiamondsRecommendModel modelWithJSON:responseObject[@"DiamondsRecommend"]];
        
        // 2. 列表数据
        CGFloat cellImageH = 65 * kScale + 40;
        [self.dataArray removeAllObjects];
        [self.allSubDetailModelsArray removeAllObjects];
        for (NSDictionary *dic in responseObject[@"StatisticsDetail"]) {
            TTShopCartModel *model = [TTShopCartModel modelWithJSON:dic];
            // 为了给cell设置高度，添加了一个 TTShopCartMultyModel
            for (TTShopCartSubModel *subModel in model.DataList) {
                // 把模型添加到数组中
                [self.allSubDetailModelsArray addObjectsFromArray:subModel.Data];
                // 在这里计算高度
                if (subModel.Data.count > 1) {
                    TTShopCartMultyModel *multyModel = [TTShopCartMultyModel setArray:subModel.Data title:subModel.Title];
                    multyModel.cellHeight = 0;
                    multyModel.isSelect = NO;
                    subModel.multyModel = multyModel;
                    // 提前计算高度，要不刷新的时候页面会跳，因为tableview计算高度需要时间
                    for (TTShopCartSubDetailModel *dModel in subModel.Data) {
//                        SCREEN_WIDTH - 105 * kScale - 20
                        if (dModel.GoodsType == 1) {
                            // 裸石
                            dModel.h = cellImageH;
                            multyModel.cellHeight += dModel.h;
                        } else {
                            dModel.h = [self calculateContentHeightWithModel:dModel cellImageH:cellImageH];
                            multyModel.cellHeight += dModel.h;
                        }
                    }
                } else {
                    TTShopCartSubDetailModel *dModel = subModel.Data.firstObject;
                    if (dModel.GoodsType == 1) {
                        // 裸石
                        dModel.h = cellImageH;
                    } else {
                        dModel.h = [self calculateContentHeightWithModel:dModel cellImageH:cellImageH];
                    }
                }
            }
            [self.dataArray addObject:model];
        }
        
        self.emptyView.hidden = self.dataArray.count > 0;
        
        self.allSelectBtn.selected = NO;
        self.totalLabel.text = @"合计:￥0";
        self.totalPrice = 0.00;
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView reloadData];
        
        NSInteger closeCount = [USER_DEFAULT integerForKey:shopCartCloseCount];
        if (closeCount < 3) {
            [self addTopView];
        }
        [self addBottomView];
        
//        [[TTLoginSingle sharedSingle].shopCartSelectBtnSubject sendNext:@(1)];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        @strongify(self)
        self.emptyView.hidden = NO;
        [self.tableView.mj_header endRefreshing];
        
    } showLoadingInView:self.tableView];
}

- (CGFloat)calculateContentHeightWithModel:(TTShopCartSubDetailModel *)model cellImageH:(CGFloat)cellImageH
{
    NSString *content = [model.GoodsDescribe componentsJoinedByString:@"\n"];
    CGFloat contentH = [content boundingRectWithSize:CGSizeMake(SCREEN_WIDTH - 105 * kScale - 20, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:12]} context:nil].size.height + 5;
    CGFloat sh = contentH + 35 + 35 + 27;
    sh = sh > cellImageH ? sh : cellImageH;
    return sh;
}

#pragma mark - TTShopCartDiamondViewCellDelegate, TTShopCartCommodityViewCellDelegate, TTShopCartMultyViewCellDelegate
- (void)clickLookCertificateWithModel:(TTShopCartSubDetailModel *)model
{
    // 查看证书
    [TTLoginSingle lookCertificateWithUrlString:model.CertPic];
}

- (void)lookDiamondDetailWithMultyViewCell:(TTShopCartMultyViewCell *)cell goodsBarCode:(NSString *)goodsBarCode
{
    @weakify(self)
    TTDiamondDetailViewController *diamondDetailVC = [[TTDiamondDetailViewController alloc] initWithDiamondModel:nil diamondID:goodsBarCode];
    diamondDetailVC.dismissBlock = ^{
        @strongify(self)
        [self getShopCartData];
    };
    [[LLRouteTool getCurrentNavigationController] pushViewController:diamondDetailVC animated:YES];
}


- (void)longGestureActionInDiamondViewCell:(TTShopCartDiamondViewCell *)cell deleteModel:(TTShopCartSubDetailModel * _Nullable)deleteModel
{
    [self deleteHintWithModel:deleteModel];
}

- (void)longGestureActionInCommodityViewCell:(TTShopCartCommodityViewCell *)cell deleteModel:(TTShopCartSubDetailModel * _Nullable)deleteModel
{
    [self deleteHintWithModel:deleteModel];
}

- (void)shopCartMultyViewCell:(TTShopCartMultyViewCell *)cell deleteModel:(TTShopCartSubDetailModel *)deleteModel
{
    [self deleteHintWithModel:deleteModel];
}

- (void)shopCartMultyViewCell:(TTShopCartMultyViewCell *)cell deleteLuoshiModel:(TTShopCartSubDetailModel * _Nullable)deleteModel
{
    [self hintConfirmDeleteLuoshi:deleteModel];
}

- (void)clickDeleteButtonInDiamondViewCell:(TTShopCartDiamondViewCell *)cell deleteModel:(TTShopCartSubDetailModel *)deleteModel
{
    [self hintConfirmDeleteLuoshi:deleteModel];
}

- (void)hintConfirmDeleteLuoshi:(TTShopCartSubDetailModel *)deleteModel
{
    @weakify(self)
    LLSystemAlertView *alertView = [LLSystemAlertView alertViewWithTitle:@"提示" message:@"确定删除这个裸石吗？" cancelTitle:@"取消" cancelBlock:nil confirmTitle:@"确定" confirmBlock:^BOOL{
        @strongify(self)
        self.deleteModel = deleteModel;
        [self deleteShop];
        return YES;
    }];
    
    [alertView showInWindowWithBackgoundTapDismissEnable:YES];
}


- (void)deleteHintWithModel:(TTShopCartSubDetailModel *)deleteModel
{
    self.deleteModel = deleteModel;
    self.longPressAlertView = deleteModel.GoodsType == 1 ? self.longPressDeleteBtn : self.hintView;
    [LLAnimationAlertView animationAlertViewWithView:self.longPressAlertView animationType:AnimationBottomToCenter];
    
}

///删除商品
- (void)deleteShop
{
    [self.deleteIDArray removeAllObjects];
    [self.deleteIDArray addObject:self.deleteModel.Id];
    [self deleteShopCartData];
}

///加入收藏夹
- (void)collectionBtnClick
{
    NSDictionary *dic = @{
                          @"param.styleLibraryId" : self.deleteModel.StyleLibraryId
                          };
    
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] postUrlString:setCollection_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        [self.view makeToast:@"收藏成功"];
        [LLAnimationAlertView dismissView:self.longPressAlertView];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        @strongify(self)
        [LLAnimationAlertView dismissView:self.longPressAlertView];
    } showLoadingInView:self.view];
}

- (void)clickCloseBtn
{
    // 记录点击次数
    NSInteger closeCount = [USER_DEFAULT integerForKey:shopCartCloseCount];
    closeCount++;
    [USER_DEFAULT setInteger:closeCount forKey:shopCartCloseCount];
    
    [UIView animateWithDuration:0.3 animations:^{
        self.redView.alpha = 0;
    } completion:^(BOOL finished) {
        self.redView.hidden = YES;
    }];
}

- (void)addTopView
{
    if (self.redView) {
        return;
    }
    _redView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 20)];
    _redView.backgroundColor = UIColorHex(FF5E5E);
    _redView.alpha = 0.5;
    UILabel *label = [UILabel labelWithTitle:@"受金价、汇率波动影响，具体以提交订单时价格为准" color:[UIColor whiteColor] fontSize:12];
    label.numberOfLines = 0;
    label.frame = CGRectMake(10, 10, _redView.width - 50, _redView.height - 20);
    [label sizeToFit];
    [_redView addSubview:label];
    
    _redView.height = label.height + 20;
    
    UIButton *closeBtn = [UIButton createButtonWithImage:[UIImage imageNamed:@"shopcart_close"] target:self action:@selector(clickCloseBtn)];
    closeBtn.imageView.contentMode = UIViewContentModeCenter;
    closeBtn.frame = CGRectMake(_redView.width - 50, 0, 40, _redView.height);
    [_redView addSubview:closeBtn];
    
    [self.view addSubview:_redView];
    
    _redView.hidden = YES;
    
}

- (void)setupHeaderView
{
    if (self.headerView) {
        return;
    }
    
    _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 20)];
    _headerView.backgroundColor = kSeparatorColor;
    _topLabel = [UILabel labelWithTitle:@"" color:UIColorHex(666666) fontSize:12];
    _topLabel.numberOfLines = 0;
    _topLabel.frame = CGRectMake(10, 5, _headerView.width - 20, _headerView.height - 10);
    [_headerView addSubview:_topLabel];
    
    self.tableView.tableHeaderView = _headerView;
}

// 全选
- (void)allSelectButtonClick:(UIButton *)sender
{
    if (self.dataArray.count == 0) {
        return;
    }
    
    BOOL canSelect = NO;
    for (TTShopCartSubDetailModel *model in self.allSubDetailModelsArray) {
        if (model.Status.intValue == 1) {
            // 可售的
            model.isSelect = !sender.selected;
            canSelect = YES;
        }
    }
    if (canSelect) {
        sender.selected = !sender.selected;
    }
    
    [self.tableView reloadData];
    
    [[TTLoginSingle sharedSingle].shopCartSelectBtnSubject sendNext:@(1)];
}

// 去结算
- (void)gotoCalculateBtnClick
{
    TTCommitOrderViewController *commitVC = [[TTCommitOrderViewController alloc] initWithShopArray:self.selectedArray diamondModel:self.diamondModel];
    [[LLRouteTool getCurrentNavigationController] pushViewController:commitVC animated:YES];
}

- (void)addBottomView
{
    if (self.bottomView) {
        return;
    }
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, self.tableView.bottom, self.view.width, bottomViewH)];
    bottomView.backgroundColor = [UIColor whiteColor];
    bottomView.layer.shadowOffset = CGSizeMake(0, -4);
    bottomView.layer.shadowColor = UIColorHex(999999).CGColor;
    bottomView.layer.shadowOpacity = 0.2;
    bottomView.layer.shadowPath = [UIBezierPath bezierPathWithRect:bottomView.bounds].CGPath;
    [self.view addSubview:bottomView];
    self.bottomView = bottomView;
    
    _allSelectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_allSelectBtn setTitle:@"全选" forState:UIControlStateNormal];
    [_allSelectBtn setImage:[UIImage imageNamed:@"shopcart_unsel"] forState:UIControlStateNormal];
//    [_allSelectBtn setImage:[UIImage imageNamed:@"shopcart_unsel"] forState:UIControlStateHighlighted];
    [_allSelectBtn setImage:[UIImage imageNamed:@"shopcartlist_sel"] forState:UIControlStateSelected];
    [_allSelectBtn setTitleColor:UIColorHex(333333) forState:UIControlStateNormal];
    _allSelectBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [_allSelectBtn addTarget:self action:@selector(allSelectButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    _allSelectBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);
    [bottomView addSubview:_allSelectBtn];
    [_allSelectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.height.equalTo(bottomView);
        make.left.mas_equalTo(10);
        make.width.mas_equalTo(60);
    }];
    
    _totalLabel = [UILabel labelWithTitle:@"合计:￥0" color:UIColorHex(333333) fontSize:16];
    [bottomView addSubview:_totalLabel];
    [_totalLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.height.equalTo(bottomView);
        make.left.equalTo(self.allSelectBtn.mas_right).mas_offset(15 * kScale);
    }];
    
    
    _calculateBtn = [UIButton createButtonWithTitle:@"去结算" titleColor:[UIColor whiteColor] titleFont:[UIFont systemFontOfSize:15] backgroundColor:[UIColor grayColor] target:self action:@selector(gotoCalculateBtnClick)];
    // UIColorHex(6928BA)
    _calculateBtn.enabled = NO;
    [bottomView addSubview:_calculateBtn];
    [_calculateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.height.right.equalTo(bottomView);
        make.width.mas_equalTo(120 * kScale);
    }];
    
    
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.tableFooterView = [UIView new];
        [_tableView registerClass:[TTShopCartDiamondViewCell class] forCellReuseIdentifier:luoshiCellID];
        [_tableView registerClass:[TTShopCartCommodityViewCell class] forCellReuseIdentifier:commodityCellID];
        [_tableView registerClass:[TTShopCartMultyViewCell class] forCellReuseIdentifier:multyCellID];
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.mas_topLayoutGuideBottom);
            make.left.right.equalTo(self.view);
           make.bottom.equalTo(self.mas_bottomLayoutGuideTop).mas_offset(-bottomViewH);
        }];
    }
    return _tableView;
}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (NSMutableArray *)allSubDetailModelsArray
{
    if (!_allSubDetailModelsArray) {
        _allSubDetailModelsArray = [NSMutableArray array];
    }
    return _allSubDetailModelsArray;
}

- (NSMutableArray<NSString *> *)deleteIDArray
{
    if (!_deleteIDArray) {
        _deleteIDArray = [NSMutableArray array];
    }
    return _deleteIDArray;
}

- (NSMutableArray<TTShopCartSubDetailModel *> *)deleteArray
{
    if (!_deleteArray) {
        _deleteArray = [NSMutableArray array];
    }
    return _deleteArray;
}

- (NSMutableArray<TTShopCartSubDetailModel *> *)selectedArray
{
    if (!_selectedArray) {
        _selectedArray = [NSMutableArray array];
    }
    return _selectedArray;
}

- (void)gotoHomePage
{
    [LLRouteTool gotoHomeViewController];
}

- (UIView *)hintView
{
    if (!_hintView) {
        _hintView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 80, 80)];
        _hintView.backgroundColor = [UIColor whiteColor];
        _hintView.layer.cornerRadius = 10;
        
        UIButton *collectionBtn = [UIButton createButtonWithTitle:@"加入收藏夹" titleColor:kMainColor titleFont:[UIFont systemFontOfSize:16] backgroundColor:nil target:self action:@selector(collectionBtnClick)];
        collectionBtn.frame = CGRectMake(0, 0, _hintView.width, 40);
        [_hintView addSubview:collectionBtn];
        
        [LLLineUtilies addLineInView:_hintView startPoint:CGPointMake(0, 40) endPoint:CGPointMake(_hintView.width, 40) lineColor:kSeparatorColor];
        
        UIButton *delBtn = [UIButton createButtonWithTitle:@"删除" titleColor:kMainColor titleFont:[UIFont systemFontOfSize:16] backgroundColor:nil target:self action:@selector(deleteShop)];
        delBtn.frame = CGRectMake(0, 40, _hintView.width, 40);
        [_hintView addSubview:delBtn];
        
        
    }
    return _hintView;
}

- (UIButton *)longPressDeleteBtn
{
    if (!_longPressDeleteBtn) {
        _longPressDeleteBtn = [UIButton createButtonWithTitle:@"删除" titleColor:kMainColor titleFont:[UIFont systemFontOfSize:16] backgroundColor:[UIColor whiteColor] cornerRadius:10 target:self action:@selector(deleteShop)];
        _longPressDeleteBtn.frame = CGRectMake(0, 0, SCREEN_WIDTH - 80, 40);
    }
    return _longPressDeleteBtn;
}

- (UIView *)emptyView
{
    if (!_emptyView) {
        _emptyView = [[UIView alloc] init];
        _emptyView.hidden = YES;
        [self.tableView addSubview:_emptyView];
        [_emptyView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
        
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"shopcartempty"]];
        imageView.frame = CGRectMake(0, 0, 100, 100);
        
        UILabel *label = [UILabel labelWithTitle:@"购物车还空空如也哟~" color:UIColorHex(666666) fontSize:15];
        
        UIButton *btn = [UIButton createButtonWithTitle:@"去逛逛" titleColor:kMainColor titleFontSize:18 borderColor:kMainColor cornerRadius:15 contentEdgeInsets:UIEdgeInsetsMake(7, 18, 7, 18) target:self action:@selector(gotoHomePage)];
        
        UIStackView *stVeiw = [[UIStackView alloc] init];
        stVeiw.axis = UILayoutConstraintAxisVertical;
        stVeiw.distribution = UIStackViewDistributionEqualCentering;
        stVeiw.alignment = UIStackViewAlignmentCenter;
        stVeiw.spacing = 15;
        [stVeiw addArrangedSubview:imageView];
        [stVeiw addArrangedSubview:label];
        [stVeiw addArrangedSubview:btn];
        [_emptyView addSubview:stVeiw];
        [stVeiw mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(100);
            make.centerX.equalTo(_emptyView);
            make.width.equalTo(self.view);
            make.height.mas_equalTo(190);
        }];
        
        [_emptyView layoutIfNeeded];
        btn.layer.cornerRadius = btn.height * 0.5;
        
    }
    return _emptyView;
}


- (void)dealloc
{
    NSLog(@"[< %@ >] 释放了", self.className);
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
